#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/06/27
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from project.flasky import db
from project.define import db_logger


DataName = "显示屏"
TableName = "app_device_led"

class DeviceLED168(db.Model):
    """
    LED控制器
    """
    __tablename__ = TableName
    # 设备编号
    LEDID = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False)
    # 闸机名称
    GateID = db.Column(db.String(16), nullable=False)
    # 闸机名称
    GateName = db.Column(db.String(16), nullable=False)
    # 闸机地址
    LEDAddr = db.Column(db.String(32), nullable=False, unique=True)
    # 設備端口
    Port = db.Column(db.Integer,  nullable=False)
    # 閘機位置
    Position = db.Column(db.String(32))

    def __init__(self, **kwargs) -> None:
        super().__init__()
        self.GateID = kwargs.get('GateID')
        self.GateName = kwargs.get('GateName')
        self.LEDAddr = kwargs.get('LEDAddr')
        self.Port = kwargs.get('Port')
        self.Position = kwargs.get('Position')

    def to_dict(self):
        """
        转换键值对
        """
        return dict([(c.name, getattr(self, c.name)) for c in self.__table__.columns])

    @staticmethod
    def selected_data(**kwargs):
        """
        选中数据
        """
        led_id = kwargs.get('LEDID')
        if led_id:
            return DeviceLED168.query.filter_by(LEDID=led_id).first()

    @staticmethod
    def columns_name():
        """
        数据表标题
        """
        ColumnName = {
            'LEDID': 'LED編號', 'GateID':'車場閘機','GateName': '閘機名稱', 'LEDAddr': 'IP地址', 'Port':'設備端口', 'Position': '閘機位置'}
        return ColumnName

    @staticmethod
    def generate_filters(**kwargs):
        """
        筛选器
        """
        filters = set()
        for k, v in kwargs.items():
            if v:
                if hasattr(DeviceLED168, k):
                    if k == 'GateName':
                        filters.add(DeviceLED168.GateName == v)
                    elif k == 'Position':
                        filters.add(DeviceLED168.Position.like(f"%{v}%"))
        return filters

    @staticmethod
    def insert_data(**kwargs):
        """
        新增
        """
        try:
            r = DeviceLED168(**kwargs)
            db.session.add(r)
            db.session.commit()
            db_logger.debug(f"{TableName} => 新增{DataName}成功：{kwargs}")
            return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 新增{DataName}失败：{kwargs} 原因：{e}")

    @staticmethod
    def delete_data(**kwargs):
        """
        删除
        """
        try:
            r = DeviceLED168.selected_data(**kwargs)
            if r:
                db.session.delete(r)
                db.session.commit()
                db_logger.debug(f"{TableName} => 删除{DataName}D成功：{kwargs}")
                return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 删除{DataName}失败：{kwargs} 原因：{e}")

    @staticmethod
    def modify_data(**kwargs):
        """
        修改
        """
        try:
            update = False
            r = DeviceLED168.selected_data(**kwargs)
            if r:
                for k, v in kwargs.items():
                    if hasattr(r, k):
                        if getattr(r, k) != v:
                            setattr(r, k, v)
                            update = True
                if update:
                    try:
                        db.session.commit()
                        db_logger.debug(f"{TableName} => 更新{DataName}成功：{kwargs}")
                        return r.to_dict()
                    except Exception as e:
                        db.session.rollback()
                        db_logger.error(f"{TableName} => 更新{DataName}失败：{kwargs} 原因：{e}")
                else:
                    return "ignore"
        except Exception as e:
            db_logger.error(f"{TableName} => 更新{DataName}参数错误：{kwargs} 原因：{e}")

    @staticmethod
    def table_init(*args):
        """
        数据初始化
        """
        demo_data = {'Entrance':{'LEDAddr': '192.168.0.40', 'Port':10000},'Exit':{'LEDAddr': '192.168.0.41', 'Port':10000}}
        for g in args:
            if isinstance(g, dict):
                gate_type = g.get('GateType')
                if gate_type:
                    led = demo_data.get(gate_type)
                    if led:
                        addr = led.get('LEDAddr')
                        r = DeviceLED168.query.filter_by(LEDAddr=addr).first()
                        if not r:
                            g.update(**led)
                            DeviceLED168.insert_data(**g)